package com.zhl.study.controller;

import com.zhl.study.base.ResponseFactory;
import com.zhl.study.base.Result;
import com.zhl.study.service.IDatasourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * DorisController.java
 * @Description
 * @Author zhaol@leadsea.net
 * @Date 2024/9/4 上午10:52
 **/
@Slf4j
@RestController
@RequestMapping("api/")
@Api(value = "doris数据源", tags = "doris数据源")
public class DatasourceController {

    @Resource(name = "currentDatasourceService")
    private IDatasourceService currentDatasourceService;
    @Resource(name = "dorisDatasourceService")
    private IDatasourceService dorisDatasourceService;

    @GetMapping("/tables")
    @ApiOperation(httpMethod = "GET", value = "获取列表")
    public Result<List<String>> getTableNames(String datasource) {
        List<String> tables;
        if ("doris".equalsIgnoreCase(datasource)){
            tables = dorisDatasourceService.getTableNames();
        }else {
            tables = currentDatasourceService.getTableNames();
        }
        return ResponseFactory.ok(tables);
    }

    @GetMapping("/fields")
    @ApiOperation(httpMethod = "GET", value = "获取字段")
    public Result<List<String>> fields(String datasource, String tableName) {
        List<String> fields;
        if ("doris".equalsIgnoreCase(datasource)){
            fields = dorisDatasourceService.fields(tableName);
        } else {
            fields = currentDatasourceService.fields(tableName);
        }
        return ResponseFactory.ok(fields);
    }

    @GetMapping("/execute")
    @ApiOperation(httpMethod = "GET", value = "执行查询")
    public Result<List<Map<String, Object>>> executeQuery(String datasource, String sql) {
        List<Map<String, Object>> data;
        if ("doris".equalsIgnoreCase(datasource)){
            data = dorisDatasourceService.executeQuery(sql);
        } else {
            data = currentDatasourceService.executeQuery(sql);
        }
        return ResponseFactory.ok(data);
    }
}
